// 机构详情
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { useLocation } from 'react-router';
import { parse } from 'qs';
import { Card } from 'antd';
import * as experienceApi from '~/apis/experience/experienceApi';
import { config } from '~/config/config';
import './index.local.sass';

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const setCardTitle = (title: string) => (
  <div className="card-title">
    <span className="title-icon">&nbsp;</span>
    <span>{title}</span>
  </div>
);


const CaseDetail = observer(() => {
  const location = useLocation();
  // const history = useHistory();

  const querryParams = parse(location.search, { ignoreQueryPrefix: true });
  const state = useLocalStore(() => ({
    id: querryParams.id || '',
    expName: '',
    time: 0,
    caseUrl: [] as Array<string>,
    loading: false,
  }));

  // 表单填充
  const fillForm = (formData: any) => {
    const {
      expName,
      createTime,
      expUrl,
    } = formData;
    state.expName = expName;
    state.time = createTime;

    const formatedList = [] as Array<string>;

    expUrl.split(',').forEach((v: any) => {
      formatedList.push(`${config.ossUrl}${v as string}`);
    });
    state.caseUrl = formatedList;
  };

  const initData = (id: any) => {
    experienceApi.getCase(id).then((res) => {
      fillForm(res.data);
    });
  };

  const sendUrl = (url: any) => {
    const w = window.open('about:blank') as Window;
    // 要打开的新页面的url
    w.location.href = url;
  };

  // 根据id 查询机构详情
  React.useEffect(() => {
    initData(state.id);
  }, []);


  return (
    <div>
      <Card
        {...cardConfig}
        title={
          setCardTitle('Case Infomation')
        }
        className="info-card"
      >
        <ul className="detail-container">
          <li className="detail-content">
            <p className="content-left">Case Name:</p>
            <p
              className="content-right">{state.expName ? state.expName : ''}</p>
          </li>
          <li className="detail-content">
            <p className="content-left">Publish Time:</p>
            <p className="content-right">{state.time ? state.time : ''}</p>
          </li>
          <li className="detail-content">
            <p className="content-left">Related Cases:</p>
            <p className="content-right">
              {
                state.caseUrl.map((c: any) => <span key={c}><a key={c} onClick={() => sendUrl(c)}>{c}</a> <br /></span>)
              }
            </p>
          </li>
        </ul>
      </Card>

    </div>
  );
});
export default CaseDetail;
